<template>
  <div>
    <a-card>
      <a-form :form="form">
        <a-row :gutter="12">
          <a-col :md="12" :sm="12">
            <a-form-item
              label="国内生课程"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select v-decorator="['gnskcdm',
                {
                  rules: [{ required: true, message: '请选择国内生课程!' }],
                }]" showSearch :filterOption="filterOption">
                <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
                <a-select-option v-for="(i,index) in selectMenu.courseList" :key="index" :value="i.kch">{{ i.kch }}{{
                  i.kcmc }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-item
              label="国际生课程"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select v-decorator="['gjskcdm',
                {
                  rules: [{ required: true, message: '请选择国际生课程!' }],
                }]" showSearch :filterOption="filterOption">
                <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
                <a-select-option v-for="(i,index) in selectMenu.courseList" :key="index" :value="i.kch">{{ i.kch }}{{
                  i.kcmc }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-item
              label="培养层次"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select v-decorator="['pyccm',
                {
                  rules: [{ required: true, message: '请选择培养层次!' }],
                }]" showSearch :filterOption="filterOption">
                <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
                <a-select-option v-for="(i,index) in selectMenu.pyccList" :key="index" :value="i.kch">{{ i.kch }}{{
                  i.kcmc }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-item
              label="培养模式"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-select v-decorator="['pymsm',
                {
                  rules: [{ required: true, message: '请选择培养模式!' }],
                }]" showSearch :filterOption="filterOption">
                <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
                <a-select-option v-for="(i,index) in selectMenu.pymsList" :key="index" :value="i.kch">{{ i.kch }}{{
                  i.kcmc }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item
              label="学分"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}"
            >
              <a-input v-decorator="['xf']" disabled/>
            </a-form-item>
          </a-col>
          <a-form-item :wrapperCol="{span: 39, offset: 5}" style="margin-top: 30px;">
            <a-button :loading="loading" type="primary" @click="toNext">{{ last ? '确定提交' : '下一步' }}</a-button>
          </a-form-item>
        </a-row>
      </a-form>
    </a-card>

  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import DetailList from '~/tool/DetailList'
  import ARow from "ant-design-vue/es/grid/Row";
  import ACol from "ant-design-vue/es/grid/Col";

  const DetailListItem = DetailList.Item

  export default {
    data() {
      return {
        form: this.$form.createForm(this, {name: "form"}),
        selectMenu: {},
        kcLoading: false,
        chooseVisible: false,
        chooseType: null,
        chooseTitle: '',
        editId: null,
        last: false,
        loading: false,
        pkInfo: {xkrsxdMin: 3},
        formItemLayout: {
          labelCol: {span: 8},
          wrapperCol: {span: 14},
        },
        itemShow: true,
      }
    },
    components: {ACol, ARow},
    computed: {
      ...mapState({
        TYPE0125: state => state.app['TYPE0125'],
        TYPE0126: state => state.app['TYPE0126'],
        TYPE0072: state => state.app['TYPE0072'],
        TYPE0343: state => state.app['TYPE0343'],
        TYPE0344: state => state.app['TYPE0344'],
        TYPE0522: state => state.app['TYPE0522'],
        TYPE0331: state => state.app['TYPE0331'] || [],
      })
    },
    created() {
      this.$store.dispatch('app/setDictionary', 'TYPE0125')
      this.$store.dispatch('app/setDictionary', 'TYPE0126')
      this.$store.dispatch('app/setDictionary', 'TYPE0072')
      this.$store.dispatch('app/setDictionary', 'TYPE0343')
      this.$store.dispatch('app/setDictionary', 'TYPE0344')
      this.$store.dispatch('app/setDictionary', 'TYPE0331')
      this.$store.dispatch('app/setDictionary', 'TYPE0522')
      this.initSelectMenu()
      if (this.$route.query.id) {
        this.editId = this.$route.query.id
        this.getInfo(this.editId)
      } else {
        this.form.setFieldsValue(this.pkInfo)
      }
    },
    methods: {
      initSelectMenu() {
        let allRequest = [
          this.$api.base.collegeAll()
        ]
        Promise.all(allRequest).then(res => {
          this.selectMenu = {
            yxList: res[0].data
          }
        })
      },
      getInfo(id) {
        this.$api.cultivate.pkDetail(id).then(res => {
          this.pkInfo = res.data
          let infoData = res.data
          if (infoData.kkyxm) {
            this.yxChange(infoData.kkyxm)
          }
          let keys = Object.keys(this.form.getFieldsValue())
          let obj = {}
          keys.forEach(key => {
            if (key == "sklxm") {
              if (infoData[key] == "01") {
                this.itemShow = true
              } else {
                this.itemShow = false
              }
              obj[key] = infoData[key]
            } else {
              obj[key] = infoData[key]
            }
          })
          this.form.setFieldsValue(obj)

        })
      },
      filterOption(value, op) {
        return op.componentOptions.children[0].text.indexOf(value) !== -1
      },
      sklxChange(code) {
        if (code == "01") {
          this.itemShow = true
        } else {
          this.pkInfo.xqmc = ""
          this.pkInfo.jslxmc = ""
          this.pkInfo.classroomNo = ""
          this.pkInfo.capacity = ""
          this.form.resetFields(['skzlxm', 'skz', 'jskj', 'kskj', 'xkrsxdMin', 'xkrsxd'])
          this.itemShow = false
        }
        this.$forceUpdate()
      },
      yxChange(code) {
        this.form.setFieldsValue({kcbm: ''})
        this.$set(this.selectMenu, 'courseList', [])
        if (code) {
          this.kcLoading = true
          this.$api.cultivate.courseAll({kcssyxm: code}).then(res => {
            this.$set(this.selectMenu, 'courseList', res.data)
          }).finally(() => {
            this.kcLoading = false
          })
        } else {
          this.$set(this.selectMenu, 'courseList', [])
        }
      },
      kcChange(kch) {
        let kc = this.selectMenu.courseList.find(kc => {
          return kc.kch === kch
        })
        this.form.setFieldsValue({
          xs: kc.zxs,
          xf: kc.xf
        })
      },
      toLast() {
        this.last = false
      },
      toNext() {
        if (this.last) {
          // if(!this.editId){
          //   this.$message.warning('课程信息主键丢失，请刷新浏览器后重试')
          //   return
          // }
          if (!this.pkInfo.rkjszgh) {
            this.$message.warning('请选择任课教师')
            return
          }
          if (!this.pkInfo.classroomNo && this.itemShow) {
            this.$message.warning('请选择教室')
            return
          }
          let apiFn = this.editId ? 'pkUpdate' : 'pkAdd'
          this.form.validateFields((err, values) => {
            if (err) {
              return;
            }
            const xkrsxd = this.form.getFieldValue('xkrsxd');
            const xkrsxdMin = this.form.getFieldValue('xkrsxdMin');
            if (xkrsxdMin > xkrsxd) {
              this.$message.error("最大选课人数必须大于等于最小选课人数")
              return;
            }
            if (xkrsxd > this.pkInfo.capacity) {
              this.$message.error("重新设置最大选课人数或者重新选择教室")
              return;
            }
            if (xkrsxdMin > this.pkInfo.capacity) {
              this.$message.error("重新设置最小选课人数或者重新选择教室")
              return;
            }
            let data = {
              ...values,
              id: this.editId,
              gh: this.pkInfo.rkjszgh,
              sm: this.form.getFieldValue('rkjssm'),
              classroomNo: this.pkInfo.classroomNo
            }
            if (!this.itemShow) {
              delete data.classroomNo
            }
            this.$api.cultivate[apiFn](data).then(res => {
              this.$message.success(res.msg)
              this.goBack()
            })
          })
          // this.$api.cultivate.saveTeacherAndClassroom({
          //   id: this.editId,
          //   gh: this.pkInfo.rkjszgh,
          //   sm: this.form.getFieldValue('rkjssm'),
          //   classroomNo: this.pkInfo.classroomNo
          // }).then(res => {
          //   this.$message.success(res.msg)
          //   this.goBack()
          // })
        } else {
          if (!this.editId) {
            this.form.validateFields((err, values) => {
              if (err) {
                return
              }
              // this.loading = true
              // this.$api.cultivate.pkAdd(values).then(res => {
              //   this.loading = false
              //   this.editId = res.data.id
              this.last = true
              //   this.$message.success(res.msg)
              // })
            })
          } else {
            this.form.validateFields((err, values) => {
              if (err) {
                return
              }
              this.last = true
            })
            // this.last = true
            // let reset = false
            // if(this.pkInfo.kkxn !== this.form.getFieldValue('kkxn')){
            //   reset = true;
            // }
            // if(this.pkInfo.kkxqm !== this.form.getFieldValue('kkxqm')){
            //   reset = true;
            // }
            // if(this.pkInfo.skzlxm !== this.form.getFieldValue('skzlxm')){
            //   reset = true;
            // }
            // if(this.pkInfo.skz !== this.form.getFieldValue('skz')){
            //   reset = true;
            // }
            // if(this.pkInfo.ksz !== this.form.getFieldValue('ksz')){
            //   reset = true;
            // }
            // if(this.pkInfo.jsz !== this.form.getFieldValue('jsz')){
            //   reset = true;
            // }
            // if(this.pkInfo.kskj !== this.form.getFieldValue('kskj')){
            //   reset = true;
            // }
            // if(this.pkInfo.jskj !== this.form.getFieldValue('jskj')){
            //   reset = true;
            // }
            // if(reset){
            //   this.$confirm({
            //     title: '提示?',
            //     content: '更新排课信息将清空已选任课教师、教室等信息，您确定要重新编辑吗？',
            //     centered: true,
            //     onOk: () => {
            //       this.postSave()
            //       this.pkInfo = {}
            //     },
            //     onCancel: () => {
            //     }
            //   })
            // }else{
            //   this.postSave()
            // }
          }
        }
      },
      postSave() {
        this.form.validateFields((err, values) => {
          if (err) {
            return
          }
          this.loading = true
          let params = Object.assign({
            id: this.editId
          }, values)
          this.$api.cultivate.pkUpdate(params).then(res => {
            this.loading = false
            this.last = true
            this.$message.success(res.msg)
          })
        })
      },
      showChoose(type) {
        this.$refs.choose.searchForm = Object.assign({}, this.form.getFieldsValue())
        // this.$refs.choose.teacherNote = this.pkInfo.rkjssm
        this.chooseVisible = true
        this.chooseType = type
        this.chooseTitle = (type === 'teacher' ? '选择教师' : '选择教室')
      },
      moreThanCapacity(rule, value, callback) {
        if (this.pkInfo.capacity && value > this.pkInfo.capacity) {
          callback("输入值不能大于教室最大容量值")
        }
        callback();
      },

      updatePk(data) {
        this.pkInfo = Object.assign(this.pkInfo, data);
        var params = ["xkrsxd", "xkrsxdMin"];
        this.form.validateFields(params, {}, (err, values) => {
          if (values["xkrsxd"] > data.capacity) {
            this.$message.error("重新设置最大选课人数或者重新选择教室")
          }
          if (values["xkrsxdMin"] > data.capacity) {
            this.$message.error("重新设置最小选课人数或者重新选择教室")
          }

        })
      },
      goBack() {
        this.$router.back()
      }
    }
  }
</script>

<style>

</style>
